import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { useUpdateEffect } from '@umijs/hooks';
import { Tooltip, Row, Col, Card, Form, Input, Button, Modal } from 'antd';
import dynamic from 'umi/dynamic';
import LoadingComponent from '@/components/PageLoading/index';
import SlickTable from '@/components/SlickTable';
import useSlickTableTemp from '@/hooks/useSlickTableTemp';
import request from '@/utils/request';
import styles from './styles.less';

const { info, success, warning } = Modal;
const FormItem = Form.Item;

const namespace = 'flowExtendConfig';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

// 判断空对象
const isEmptyObject = obj => {
  if (Object.keys(obj).length === 0) {
    return true;
  }
  return false;
};

const FlowLimitTimeCfg = dynamic({
  loader: () => import('./components/FlowLimitTimeCfg'),
  loading: LoadingComponent,
});

function FlowTacheConfig(props) {
  const { getFieldDecorator } = props.form;
  const [params, setParams] = useState({}); // 查询条件
  const [selectRecord, setSelectRecord] = useState({}); // 选中的行记录
  const [limitTimeVisibleFlag, setLimitTimeVisibleFlag] = useState(false); // 设置时限弹窗
  const [selectRowId, setSelectRowId] = useState(null);

  // 初始化表格数据
  const { tableProps } = useSlickTableTemp(
    { pageSize: 10 },
    'pmc/pms/pmOrderFlowDef/queryPage',
    params
  );

  useUpdateEffect(() => {
    if (isEmptyObject(props.selectRecord)) {
      setParams({
        ...params,
      });
    }
  }, [props.selectRecord]);

  // useEffect(()=>{
  //   if(!isEmptyObject(props.selectCatalog)){
  //     // request('/project/OrderFlowExecController/modifyOrderFlowExec.do',{
  //     //   data: submintData
  //     // }).then(res => {
  //     //   if (res.resultCode && res.resultCode === 'TRUE') {
  //     //       // props.setUrgeTimeCfgFlag(false);
  //     //       props.handleDealModeCallBack(false);
  //     //   } else {
  //     //     info({title: "提交失败", content: (res.resultMsg)});
  //     //   }
  //     // });
  //   }
  // },[props.selectCatalog])

  // 通过dva存当前需要传递的数据
  const saveSelectRecord = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectRecord`,
      payload: params,
    });
  };

  const initData = () => {};

  // 初始化
  useEffect(() => {
    initData();
  }, []);

  const handleQuery = () => {
    const formData = props.form.getFieldsValue();
    formData.pageSize = 10;
    formData.pageNum = 1;
    formData.gb_reset = true;
    setParams(formData);
  };

  const handleReset = () => {
    props.form.resetFields(); // 这是重置为默认值
  };

  // 表格选中
  const handleSelectRows = record => {
    if (record != null) {
      setSelectRecord(record);
      saveSelectRecord(record);
    } else {
      setSelectRecord({});
      saveSelectRecord({});
    }
  };

  // 刷新表格
  const reloadGrid = () => {
    setParams({
      ...params,
    });
  };

  // 环节时限模态框控制方法
  const handleLimitTimeVisible = visibleFlag => {
    setLimitTimeVisibleFlag(visibleFlag);
  };
  // 环节时限回调处理
  const handleLimitTimeCallBack = resData => {
    reloadGrid();
  };
  // 环节时限回调方法
  const handleLimitTimeCallBackMethods = {
    handleLimitTimeVisible,
    handleLimitTimeCallBack,
  };

  const checkSelectRow = () => {
    if (isEmptyObject(selectRecord)) {
      warning({ title: '请先选中一条记录' });
      return false;
    }
    return true;
  };

  // 设置环节时限
  const handleLimitTime = () => {
    if (checkSelectRow()) {
      handleLimitTimeVisible(true);
    }
  };

  const cellStyle = {
    maxWidth: 200,
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    textOverflow: 'ellipsis',
    cursor: 'pointer',
  };

  const columns = [
    {
      title: '流程名称',
      dataIndex: 'flowName',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '流程编码',
      dataIndex: 'flowCode',
    },
    {
      title: '完成时限',
      dataIndex: 'limitValue',
    },
    {
      title: '告警时限',
      dataIndex: 'alertValue',
    },
    {
      title: '时间单位',
      dataIndex: 'timeUnitName',
    },
  ];

  return (
    <div>
      <Card
        title="流程扩展配置"
        className="cute"
        style={{ height: '60%' }}
        extra={
          <div>
            <Button
              className="margin-left"
              type="primary"
              onClick={() => {
                handleLimitTime();
              }}
            >
              设置流程时限
            </Button>
          </div>
        }
      >
        <Form style={{ marginBottom: 10 }}>
          <Row>
            <Col span={6}>
              <FormItem label="流程编码" {...formItemLayout}>
                {getFieldDecorator('flowCode')(<Input />)}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem label="流程名称" {...formItemLayout}>
                {getFieldDecorator('flowName')(<Input />)}
              </FormItem>
            </Col>
          </Row>
          <div style={{ textAlign: 'center' }}>
            <Button type="primary" className="margin-right" onClick={handleQuery}>
              查询
            </Button>
            <Button type="default" onClick={handleReset}>
              重置
            </Button>
          </div>
        </Form>
        <SlickTable
          rowKey={record => record.flowId}
          columns={columns}
          {...tableProps}
          scroll={{ x: 'max-content' }}
          rowClassName={record => {
            return record.flowId === selectRowId ? styles.clickRowStyle : '';
          }}
          onRow={record => {
            return {
              onClick: () => {
                setSelectRowId(record.flowId);
                handleSelectRows(record);
              },
            };
          }}
        />
      </Card>
      {limitTimeVisibleFlag ? (
        <FlowLimitTimeCfg
          selectRecord={selectRecord}
          {...handleLimitTimeCallBackMethods}
          modalVisible={limitTimeVisibleFlag}
        />
      ) : null}
    </div>
  );
}

export default connect(({ flowExtendConfig, setting }) => ({
  selectRecord: flowExtendConfig.selectRecord,
  selectCatalog: flowExtendConfig.selectCatalog,
  size: setting.size,
}))(Form.create()(FlowTacheConfig));
